// 职级管理
const { rank, rank_sys, schoolInfo, sequelize } = require('../dbConfig/index.js');
// 确保 rank_sys 模型已正确加载
if (!rank_sys) {
    throw new Error('rank_sys 模型未正确加载');
}
const { getMenuPageFunctionList } = require('../utils/menu.js')

// const sequelize = require('../dbConfig/index.js')

// 数据样例 {rank_name:'职级名称',rank_school_id:1，sys：[{page_id:1,page_function_ids:[1,2,3]}]}
const addRank = async (ctx, next) => {
    const { rank_name, rank_school_id, sys = [] } = ctx.request.body;
    console.log('addRank',sys)
    // 参数校验
    if (!rank_name || !rank_school_id) {
        ctx.body = {
            code: 400,
            msg: '职级名称和院校ID不能为空',
            data: null
        };
        return;
    }
    if (!Array.isArray(sys)) {
        ctx.body = {
            code: 400,
            msg: '权限参数必须为数组',
            data: null
        };
        return;
    }

    const transaction = await sequelize.transaction();
    try {
        // 创建职级
        const result = await rank.create({
            rank_name,
            rank_school_id
        }, { transaction });

        // 批量添加权限
        if (sys.length > 0) {
            const _arr = sys.map(item => {
				if(item.page_function_ids.length>0){
					return {
                        rank_id:result.rank_id,
						belong_to_rank_id: result.rank_id,
						page_id: item.page_id,
						page_function_ids: item.page_function_ids.join(',')
					}
				}})

            await rank_sys.bulkCreate(_arr, { transaction });
        }

        await transaction.commit();
        ctx.body = {
            code: 200,
            msg: '职级添加成功',
            data: null
        };
    } catch (error) {
        console.log(error,'报错');
        
        ctx.body = {
            code: 500,
            msg: '职级添加失败',
            data: error.message
        };
    }
}
// 获取职级
const getRank = async (ctx, next) => {
    const { school_id } = ctx.query;
    if (!school_id) {
        ctx.body = {
            code: 400,
            msg: '院校ID不能为空',
            data: null
        };
        return;
    }
    const result = await rank.findAll({
        where: {
            rank_school_id: school_id
        },
        attributes: ['rank_id', 'rank_name', 'rank_school_id'],
        include: [{
            model: rank_sys,
            attributes: ['page_id', 'page_function_ids']
        }]
    });
    ctx.body = {
        code: 200,
        msg: '职级列表',
        data: result
    };
}
// 查看职级数据详情
const getRankDetail = async (ctx, next) => {
    const { rank_id } = ctx.query;
    if (!rank_id) {
        ctx.body = {
            code: 400,
            msg: '职级ID不能为空',
            data: null
        };
        return;
    }
    const result = await rank.findOne({
        where: {
            rank_id
        },
        attributes: ['rank_id', 'rank_name', 'rank_school_id'],
        include: [{
            model: rank_sys,
            attributes: ['page_id', 'page_function_ids'],
            where:{
                belong_to_rank_id:rank_id

            }
        }]
    });
    ctx.body = {
        code: 200,
        msg: '职级详情',
        data: result
    };
}
//批量修改职级功能权限
const editRank = async (ctx, next) => {
    const { rank_id, sys = [] } = ctx.request.body;
    if(sys.length>0){
        const transaction = await sequelize.transaction();
        // 先删除职级功能权限
        await rank_sys.destroy({
            where: {
                belong_to_rank_id: rank_id
            },
            transaction
        });
        const _arr = sys.map(item => {
				if(item.page_function_ids.length>0){
					return {
                        rank_id:rank_id,
						belong_to_rank_id:rank_id,
						page_id: item.page_id,
						page_function_ids: item.page_function_ids.join(',')
					}
				}})

            await rank_sys.bulkCreate(_arr, { transaction });
        await transaction.commit();
        ctx.body = {
            code: 200,
            msg: '职级功能权限修改成功',
            data: null
        };
    }else{
        ctx.body = {
            code: 1,
            msg: '职级功能为空',
            data: null
        };
    }   
    
}
// 查询院校配置菜单，然后再根据院校菜单获取功能列表
const getPageFunction = async (ctx, next) => {
	const { school_id} = ctx.query;
    console.log(school_id,'school_id getfn')
    if(school_id==null){
        ctx.body = {
            code: 1,
            msg: '院校ID不能为空',
            data: null
        };
        return;
    }
	const {school_menu_ids} = await schoolInfo.findOne({where:{school_id}})
	const idsArray = school_menu_ids.split(',')
	let res = getMenuPageFunctionList(idsArray)
	ctx.body = {
		code:200,
		data:res,
		msg:'成功'
	}
}

module.exports = {
    addRank,
	getPageFunction,
    getRankDetail,
    editRank,
    getRank
}